package zmsdk

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"strconv"
	"time"
	"yundian/internel/pkg/authorized"
	"yundian/internel/pkg/utils"
	"yundian/internel/pkg/wechatpay"
)

const (
	pmsGetTokenURL  = "http://211.97.0.116:33001/authorize/token" //获取token测试环境url
	pmsGetMemberURL = "http://211.97.0.116:33001/member/query"    //会员查询测试环境url
	// pmsGetTokenURL  = "https://openapi.dossen.com/authorize/token" //获取token正式环境url
	// pmsGetMemberURL = https://openapi.dossen.com/member/query //会员查询正式环境url
	yhGetMemberURL         = "http://test.chinapms.com:9001/gateway/query_cards"        //测试环境
	yhGetMemberCardTypeURL = "http://test.chinapms.com:9001/gateway/get_card_type_list" //测试环境
)

//获取token
func PMSGetToken(appId string, appKey string) map[string]interface{} {
	param := &PMSGetTokenReq{}
	param.AppId = appId
	param.Timestamp = strconv.FormatInt(time.Now().Unix(), 10)
	param.NonceStr = authorized.GetRandomString(32)
	param.SignType = "MD5"
	signStr := appId + param.NonceStr + param.Timestamp + appKey
	param.Sign = utils.Str2Md5(signStr)

	payload, _ := json.Marshal(param)

	respMap, err := authorized.PostRequest(pmsGetTokenURL, map[string]string{"Content-Type": "application/json"}, bytes.NewReader(payload))

	if err != nil {
		return nil
	}
	return respMap
}

//会员查询
func PMSGetMember(token string, telephone string) map[string]interface{} {
	param := &GetMemberReq{}
	param.Telephone = telephone
	payload, _ := json.Marshal(param)
	respMap, err := authorized.PostRequest(pmsGetMemberURL, map[string]string{"Content-Type": "application/json", "access_token": token}, bytes.NewReader(payload))
	if err != nil {
		return nil
	}
	return respMap
}

//获取雅好会员信息
func YHGetMember(param map[string]interface{}) map[string]interface{} {
	paramStr := fmt.Sprintf("sob.sob_code=%s&sob.hotel_id=%s&sob.password=%s&condition.mobile=%s", param["code"], param["appid"], param["appsecret"], param["mobile"])
	log.Println("paramStr", paramStr)
	url := wechatpay.StrJoin(yhGetMemberURL, "?", paramStr)
	log.Println("url", url)
	resMap, err := authorized.GetRequest(url, map[string]string{"Content-Type": "application/json"})
	if err != nil {
		return nil
	}

	cardsMap := resMap["cards"].([]interface{})
	log.Println("7777788888", cardsMap)
	if len(cardsMap) > 0 {
		resMap = cardsMap[0].(map[string]interface{})
	}

	return resMap
}

func YHGetMemberCardType(param map[string]interface{}) map[string]interface{} {
	paramStr := fmt.Sprintf("sob.sob_code=%s&sob.hotel_id=%s&sob.password=%s&condition.mobile=%s", param["sob_code"], param["hotel_id"], param["password"], param["mobile"])
	url := wechatpay.StrJoin(yhGetMemberCardTypeURL, "?", paramStr)
	resMap, err := authorized.GetRequest(url, map[string]string{"Content-Type": "application/json"})
	if err != nil {
		return nil
	}

	return resMap
}
